package ws

import (
	"gitee.com/chenhonghua/ginorigin/log"
	"github.com/gorilla/websocket"
)

type websocketConnection struct {
	id                 string // 会话ID
	socket             *websocket.Conn
	sendContent        chan []byte // 当Send有值时，会通过管道触发Write()中的协程
	recieveMessageFunc RecieveMessageFunc
}

type RecieveMessageFunc func(Message) Message // 接收消息时的业务处理

// 接收到订阅者发送的消息
func (c websocketConnection) recieve() {
	defer func() {
		manager.unregister <- c
		c.socket.Close()
	}()
	for {
		_, message, err := c.socket.ReadMessage()
		if err != nil { // 读取发生错误，就将当前ws连接注销
			//
			log.Debugf("收到注销请求：%s，error:%#v\n", string(message), err)
			manager.unregister <- c
			// c.socket.Close()
			break
		}
		msg := Message{WsId: c.id, Sender: c.id, Content: message}
		r := c.recieveMessageFunc(msg) // 执行收到消息时的业务处理
		manager.broadcast <- r         // 发送消息给订阅者
	}
}

// 向订阅者推送消息
func (c websocketConnection) send() {
	defer func() {
		c.socket.Close()
	}()
	for {
		select {
		case message, ok := <-c.sendContent:
			if !ok {
				c.socket.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}
			c.socket.WriteMessage(websocket.TextMessage, message)
		}
		// break
	}
}
